package com.zx.centers.crawlercenter.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;



@Configuration
@MapperScan(basePackages = MysqlDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "centersSqlSessionFactory")
public class MysqlDataSourceConfig {
	static final String PACKAGE = "com.zx.centers.dataservice.mybatis.mapper.crawler";

	@Value("${centers.datasource.url}")
	private String url;

	@Value("${centers.datasource.username}")
	private String user;

	@Value("${centers.datasource.password}")
	private String password;

	@Value("com.mysql.jdbc.Driver")
	private String driverClass;

	@Value("${centers.datasource.maximumPoolSize:20}")
	private int maximumPoolSize;

	@Bean(name = "centersDataSource")
	public DataSource masterDataSource() {
		HikariDataSource dataSource = new HikariDataSource();
		dataSource.setDriverClassName(driverClass);
		dataSource.setJdbcUrl(url);
		dataSource.setUsername(user);
		dataSource.setPassword(password);
		dataSource.setMaximumPoolSize(maximumPoolSize);
		dataSource.setConnectionTestQuery("select 1");
		dataSource.setMinimumIdle(10);
		return dataSource;
	}

	@Bean(name = "centersTransactionManager")
	public DataSourceTransactionManager springTransactionManager(@Qualifier("centersDataSource") DataSource masterDataSource) {
		return new DataSourceTransactionManager(masterDataSource);
	}

	@Bean(name = "centersSqlSessionFactory")
	public SqlSessionFactory masterSqlSessionFactory(@Qualifier("centersDataSource") DataSource masterDataSource) throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(masterDataSource);
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.setMapUnderscoreToCamelCase(true);
		sessionFactory.setConfiguration(configuration);
		return sessionFactory.getObject();
	}
}
